package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"

	"gorm.io/gorm"
)

// 获取{{.Label}}列表
func GetPostInfoList(info request.QueryPost) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.SysPost{})
	var postList []model.SysPost
	if info.PostCode != "" {
		db = db.Where("`post_code` LIKE ?", "%"+info.PostCode+"%")
	}
	if info.PostName != "" {
		db = db.Where("`post_name` LIKE ?", "%"+info.PostName+"%")
	}
	if info.Status != "" {
		db = db.Where("`status` = ?", info.Status)
	}
	_ = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&postList).Error
	return postList, total, err
}

// 新增{{.Label}}
func CreatePost({{.Abbreviation}} model.SysPost) (err error) {
	if !errors.Is(global.GVA_DB.First(&{{.Abbreviation}}, "post_name = ?", {{.Abbreviation}}.PostName).Error, gorm.ErrRecordNotFound) {
		return errors.New("{{.Label}}名称已存在")
	}
	err = global.GVA_DB.Create(&{{.Abbreviation}}).Error
	return err
}

// 查询{{.Label}}
func QueryPost(id uint64) ({{.Abbreviation}} model.SysPost, err error) {
	err = global.GVA_DB.First(&{{.Abbreviation}}, id).Error
	return {{.Abbreviation}}, err
}

// 更新{{.Label}}
func UpdatePost({{.Abbreviation}} model.SysPost) (err error) {
	db := global.GVA_DB.Model(&model.SysPost{}).Where("post_id = ?", {{.Abbreviation}}.PostId)
	if errors.Is(db.Error, gorm.ErrRecordNotFound) {
		return errors.New("找不到对应的{{.Label}}")
	}

	err = db.Updates(&{{.Abbreviation}}).Error
	return err
}

// 删除{{.Label}}
func DeletePost(ids []uint64) (err error) {
	var total int64
	db := global.GVA_DB

	err = db.Where(ids).Delete(&model.SysPost{}).Error
	return err
}
